<template>
  <div>
    <header>
      <div class="header-content">
        <h1>健康数据分析</h1>
        <p class="subtitle">监测您的血压、血糖和心率健康指标,提供AI小医生帮您分析健康情况并生成健康报告</p>
      </div>
    </header>

    <div class="container">
      <div class="filters">
        <div class="filter-item">
          <label class="filter-label">用户ID</label>
          <div>{{filters.userId}}</div>
        </div>
        <div class="filter-item">
          <label class="filter-label">时间范围</label>
          <label>最近30天</label>
        </div>
        <button @click="loadData">刷新数据</button>
      </div>

      <div class="dashboard">
        <!-- 修改血压卡片显示收缩压和舒张压 -->
        <DashboardCard
            title="收缩压"
            icon="🩸"
            :value="latestData.systolic"
            :status="latestStatus.bp"
            unit="mmHg"
            normalRange="90-140"
        />
        <DashboardCard
            title="舒张压"
            icon="🩸"
            :value="latestData.diastolic"
            :status="latestStatus.bp"
            unit="mmHg"
            normalRange="60-90"
        />
        <DashboardCard
            title="血糖"
            icon="🍬"
            :value="latestData.bloodSugar"
            :status="latestStatus.bs"
            unit="mmol/L"
            normalRange="3.9-6.1"
        />
        <DashboardCard
            title="心率"
            icon="❤️"
            :value="latestData.heartRate"
            :status="latestStatus.hr"
            unit="BPM"
            normalRange="60-100"
        />

        <ChartContainer
            ref="pieChart"
            title="异常分布"
            icon="📊"
        />
      </div>

      <ChartContainer
          ref="bpChart"
          title="血压变化趋势"
          icon="📈"
      />
      <ChartContainer
          ref="bsChart"
          title="血糖变化趋势"
          icon="📊"
      />
      <ChartContainer
          ref="hrChart"
          title="心率变化趋势"
          icon="📉"
      />

      <DataTable :data="filteredData" />
    </div>

    <div class="ai-doctor">
      <h2>AI 小医生</h2>
      <button @click="sendHealthReport">生成健康报告</button>
      <div class="chat-history">
        <div v-for="(message, index) in chatMessages" :key="index" :class="['message', message.role]" v-html="parseMarkdown(message.content)"></div>
        <!-- 添加思考动画 -->
        <div v-if="isThinking" class="thinking-indicator">
          AI 正在思考中...<span class="dots">...</span>
        </div>
      </div>
      <div class="input-area">
        <input v-model="userInput" @keyup.enter="sendMessage" placeholder="输入你的问题">
        <button @click="sendMessage">发送</button>
      </div>
    </div>
    <footer>
      <p>健康数据分析平台 © 2025 | 数据每15分钟更新一次 | 健康咨询热线: 400-1234-5678</p>
    </footer>
  </div>
</template>

<script>
import { Chart } from 'chart.js/auto';
import DashboardCard from '@/views/Analysis/DashBoardCard.vue';
import ChartContainer from '@/views/Analysis/ChartContainer.vue';
import DataTable from '@/views/Analysis/DataTable.vue';
import { getHealthData } from "@/api/analysis.js";
import { ref } from "vue";
import axios from 'axios';
import { marked } from 'marked'; // 修改引入方式

const storedUser = localStorage.getItem('currentUser');
const userInfo = ref();
userInfo.value = storedUser ? JSON.parse(storedUser) : null;

export default {
  components: {
    DashboardCard,
    ChartContainer,
    DataTable
  },
  data() {
    return {
      filters: {
        userId: userInfo.value?.id || '',
        timeRange: '30',
        dataType: 'all'
      },
      healthData: [],
      charts: {},
      anomalyStats: { normal: 0, warning: 0, danger: 0 },
      chatMessages: [
        { role: 'assistant', content: '您好！我是 AI 小医生，您可以告诉我您的血压、血糖等指标，我来帮您分析健康状况。' }
      ],
      userInput: ''
    };
  },
  computed: {
    // 添加异常统计计算属性
    calculateAnomalyStats() {
      const stats = { normal: 0, warning: 0, danger: 0 };
      this.healthData.forEach(item => {
        const status = this.evaluateHealthStatus(item);
        Object.values(status).forEach(s => {
          if (s === 'normal') stats.normal++;
          if (s === 'warning') stats.warning++;
          if (s === 'danger') stats.danger++;
        });
      });
      return stats;
    },
    latestData() {
      if (this.healthData.length === 0) {
        return {
          systolic: '--',      // 收缩压
          diastolic: '--',     // 舒张压
          bloodSugar: '--',
          heartRate: '--'
        };
      }

      const latest = this.healthData[this.healthData.length - 1];
      return {
        systolic: latest.systolic !== undefined && latest.systolic !== null
            ? latest.systolic
            : '--',
        diastolic: latest.diastolic !== undefined && latest.diastolic !== null
            ? latest.diastolic
            : '--',
        bloodSugar: latest.bloodSugar !== undefined && latest.bloodSugar !== null
            ? latest.bloodSugar.toFixed(1)
            : '--',
        heartRate: latest.heartRate !== undefined && latest.heartRate !== null
            ? latest.heartRate
            : '--'
      };
    },
    latestStatus() {
      if (this.healthData.length === 0) {
        return { bp: 'loading', bs: 'loading', hr: 'loading' };
      }

      const latest = this.healthData[this.healthData.length - 1];
      return this.evaluateHealthStatus(latest);
    },
    filteredData() {
      if (this.filters.dataType === 'all') return this.healthData;

      return this.healthData.filter(item => {
        if (this.filters.dataType === 'bp') return item.systolic !== undefined;
        if (this.filters.dataType === 'bs') return item.bloodSugar !== undefined;
        if (this.filters.dataType === 'hr') return item.heartRate !== undefined;
        return true;
      });
    }
  },
  methods: {
    // 解析 Markdown 的方法
    parseMarkdown(text) {
      return marked.parse(text);
    },
    // 新增生成健康数据文本的方法
    generateHealthDataText() {
      let text = '请根据以下健康数据生成一份健康报告：\n';
      this.healthData.forEach((item, index) => {
        text += `记录 ${index + 1}：日期 ${item.date}，收缩压 ${item.systolic || '--'} mmHg，舒张压 ${item.diastolic || '--'} mmHg，血糖 ${item.bloodSugar !== undefined ? item.bloodSugar.toFixed(1) : '--'} mmol/L，心率 ${item.heartRate || '--'} BPM\n`;
      });
      return text;
    },
    // 新增发送健康报告的方法
    sendHealthReport() {
      if (this.healthData.length === 0) {
        alert('暂无健康数据，请先加载数据。');
        return;
      }
      const healthDataText = this.generateHealthDataText();
      this.userInput = healthDataText;
      this.sendMessage();
    },
    //豆包
    async sendMessage() {
      if (!this.userInput.trim()) return;
      
      // 添加用户消息到聊天记录
      this.chatMessages.push({ role: 'user', content: this.userInput });
      this.userInput = '';
      this.isThinking = true; // 开始思考，显示动画
      
      try {
        // 调用后端豆包接口，设置请求头 Content-Type 为 application/json，构造包含 messages 数组的请求数据
        const requestData = {
          model: 'doubao-seed-1-6-250615', // 根据实际情况替换模型名称
          messages: this.chatMessages
        };
        const response = await axios.post('http://localhost:8080/doubao/chat', JSON.stringify(requestData), {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        // 添加 AI 回复到聊天记录，用 Markdown 代码块封装数据
        this.chatMessages.push({ 
          role: 'assistant', 
          content: '```markdown\n' + response.data + '\n```' 
        });
      } catch (error) {
        if (error.response) {
          console.error('请求失败，状态码:', error.response.status);
          console.error('响应数据:', error.response.data);
        } else if (error.request) {
          console.error('请求已发送，但没有收到响应:', error.request);
        } else {
          console.error('请求设置出错:', error.message);
        }
        console.error('与 AI 小医生交互失败:', error);
        
        this.chatMessages.push({ role: 'assistant', content: '抱歉，与 AI 小医生交互时出现错误，请稍后再试。' });
      } finally {
        this.isThinking = false; // 结束思考，隐藏动画
      }
    },
    initPieChart() {
      const canvas = this.$refs.pieChart?.getCanvas();
      if (!canvas) return;

      // 使用计算属性获取统计数据
      const { normal, warning, danger } = this.calculateAnomalyStats;

      // 如果存在旧图表则销毁
      if (this.charts.pie) {
        this.charts.pie.destroy();
      }

      this.charts.pie = new Chart(canvas, {
        type: 'pie',
        data: {
          labels: ['正常', '警告', '危险'],
          datasets: [{
            data: [normal, warning, danger],
            backgroundColor: [
              '#4CAF50',
              '#FFC107',
              '#FF5252'
            ],
            borderWidth: 1
          }]
        },
        options: {
          responsive: true,
          plugins: {
            legend: {
              position: 'top',
            },
            title: {
              display: true,
              text: '异常分布',
              font: {
                size: 16
              }
            },
            tooltip: {
              callbacks: {
                label: function(context) {
                  const label = context.label || '';
                  const value = context.raw || 0;
                  const total = context.dataset.data.reduce((a, b) => a + b, 0);
                  const percentage = Math.round((value / total) * 100);
                  return `${label}: ${value} (${percentage}%)`;
                }
              }
            }
          }
        }
      });
    },
    evaluateHealthStatus(item) {
      const status = { bp: 'normal', bs: 'normal', hr: 'normal' };

      // 血压评估 - 分别评估收缩压和舒张压
      let systolicStatus = 'normal';
      let diastolicStatus = 'normal';

      // 收缩压评估
      if (item.systolic !== null && !isNaN(item.systolic)) {
        const systolic = item.systolic;
        if (systolic < 90) {
          systolicStatus = 'danger';
        } else if (systolic < 100) {
          systolicStatus = 'warning';
        } else if (systolic >= 180) {
          systolicStatus = 'danger';
        } else if (systolic >= 140) {
          systolicStatus = 'warning';
        }
      }

      // 舒张压评估
      if (item.diastolic !== null && !isNaN(item.diastolic)) {
        const diastolic = item.diastolic;
        if (diastolic < 60) {
          diastolicStatus = 'danger';
        } else if (diastolic < 70) {
          diastolicStatus = 'warning';
        } else if (diastolic >= 110) {
          diastolicStatus = 'danger';
        } else if (diastolic >= 90) {
          diastolicStatus = 'warning';
        }
      }

      // 取两者中最严重的状态作为血压整体状态
      if (systolicStatus === 'danger' || diastolicStatus === 'danger') {
        status.bp = 'danger';
      } else if (systolicStatus === 'warning' || diastolicStatus === 'warning') {
        status.bp = 'warning';
      } else {
        status.bp = 'normal';
      }

      // 血糖评估
      if (item.bloodSugar !== undefined && item.bloodSugar !== null) {
        const bs = item.bloodSugar;

        if (bs < 3.9) {
          status.bs = 'warning';
        } else if (bs >= 7.0) {
          status.bs = 'danger';
        } else if (bs >= 6.1) {
          status.bs = 'warning';
        }
      }

      // 心率评估
      if (item.heartRate !== undefined && item.heartRate !== null) {
        const hr = item.heartRate;

        if (hr < 50) {
          status.hr = 'danger';
        } else if (hr < 60) {
          status.hr = 'warning';
        } else if (hr > 120) {
          status.hr = 'danger';
        } else if (hr > 100) {
          status.hr = 'warning';
        }
      }

      return status;
    },
    async loadData() {
      try {
        this.healthData = await this.fetchHealthData();
        console.log('健康数据:', this.healthData);
        // 更新异常统计数据
        this.anomalyStats = this.calculateAnomalyStats;
        this.initCharts();
        this.initPieChart(); // 确保饼图被初始化
      } catch (error) {
        console.error('获取数据失败:', error);
        alert('数据加载失败，请稍后重试');
      }
    },
    fetchHealthData() {
       return new Promise(resolve => {
         setTimeout(async () => {
            const mockData = await getHealthData(userInfo.value.id);
            console.log('666',mockData)
          // 更健壮的数据转换逻辑
          const processedData = mockData.map(item => {
            return {
              ...item,
            };

            // 默认返回原始数据
            const processedData = mockData.map(item => {
            console.log('原始数据:', {
              date: item.date,
              systolic: item.systolic,
              diastolic: item.diastolic,
              bloodPressure: item.bloodPressure
            });

            return {
              ...item,
              systolic: Number(item.systolic) || null,
              diastolic: Number(item.diastolic) || null
            };
          });
          });

          resolve(processedData);
        }, 800);
       });
    },
    getChartData() {
      // 根据实际数据结构调整
      const bpData = this.filteredData.map(item => ({
        date: item.date,
        systolic: item.systolic, // 收缩压
        diastolic: item.diastolic // 舒张压
      }));

      const bsData = this.filteredData.map(item => ({
        date: item.date,
        value: item.bloodSugar
      }));

      const hrData = this.filteredData.map(item => ({
        date: item.date,
        value: item.heartRate
      }));

      return { bpData, bsData, hrData };
    },
    initCharts() {
      // 销毁现有图表
      if (this.charts) {
        Object.values(this.charts).forEach(chart => {
          if (chart && typeof chart.destroy === 'function') {
            chart.destroy();
          }
        });
      }

      const chartData = this.getChartData();
      console.log('图表数据:', chartData);

      // 初始化血压图表
      this.initBPChart(chartData.bpData);

      // 初始化血糖图表
      this.initBSChart(chartData.bsData);

      // 初始化心率图表
      this.initHRChart(chartData.hrData);
    },
    initBPChart(data) {
      const canvas = this.$refs.bpChart?.getCanvas();
      if (!canvas) {
        console.warn('血压图表Canvas未找到');
        return;
      }
      // 确保数据有效 - 过滤无效值
      const validData = data.filter(d =>
          (d.systolic !== null && !isNaN(d.systolic)) ||
          (d.diastolic !== null && !isNaN(d.diastolic))
      );

      if (validData.length === 0) {
        console.warn('血压数据为空');
        return;
      }

      const dates = validData.map(d => d.date);
      const systolicData = validData.map(d => d.systolic);
      const diastolicData = validData.map(d => d.diastolic);

      // 同时显示收缩压和舒张压
      const datasets = [
        {
          label: '收缩压',
          data: systolicData,
          borderColor: '#ff6b6b',
          backgroundColor: 'rgba(255, 107, 107, 0.1)',
          tension: 0.3,
          spanGaps: true
        },
        {
          label: '舒张压',
          data: diastolicData,
          borderColor: '#36a2eb',
          backgroundColor: 'rgba(54, 162, 235, 0.1)',
          tension: 0.3,
          spanGaps: true
        }
      ];

      this.charts.bp = new Chart(canvas, {
        type: 'line',
        data: {
          labels: dates,
          datasets: datasets
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: { position: 'top' },
            title: { display: true, text: '血压变化趋势' }
          },
          scales: {
            y: {
              title: { display: true, text: '血压 (mmHg)' },
              min: 40,
              max: 200
            },
            x: {
              ticks: {
                maxRotation: 30,
                minRotation: 30
              }
            }
          }
        }
      });
    },
    initBSChart(data) {
      const canvas = this.$refs.bsChart?.getCanvas();
      if (!canvas) {
        console.warn('血糖图表Canvas未找到');
        return;
      }

      // 确保数据有效
      const validData = data.filter(d =>
          d.value !== undefined && d.value !== null
      );

      if (validData.length === 0) {
        console.warn('血糖数据为空');
        return;
      }

      const dates = validData.map(d => d.date);
      const values = validData.map(d => d.value);

      this.charts.bs = new Chart(canvas, {
        type: 'line',
        data: {
          labels: dates,
          datasets: [{
            label: '血糖值',
            data: values,
            borderColor: '#4facfe',
            backgroundColor: 'rgba(79, 172, 254, 0.1)',
            tension: 0.3,
            spanGaps: true
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: { position: 'top' },
            title: { display: true, text: '血糖变化趋势' }
          },
          scales: {
            y: {
              title: { display: true, text: '血糖 (mmol/L)' },
              min: 2,
              max: 15
            },
            x: {
              ticks: {
                maxRotation: 30,
                minRotation: 30
              }
            }
          }
        }
      });
    },
    initHRChart(data) {
      const canvas = this.$refs.hrChart?.getCanvas();
      if (!canvas) {
        console.warn('心率图表Canvas未找到');
        return;
      }

      // 确保数据有效
      const validData = data.filter(d =>
          d.value !== undefined && d.value !== null
      );

      if (validData.length === 0) {
        console.warn('心率数据为空');
        return;
      }

      const dates = validData.map(d => d.date);
      const values = validData.map(d => d.value);

      this.charts.hr = new Chart(canvas, {
        type: 'line',
        data: {
          labels: dates,
          datasets: [{
            label: '心率',
            data: values,
            borderColor: '#42e695',
            backgroundColor: 'rgba(66, 230, 149, 0.1)',
            tension: 0.3,
            spanGaps: true
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: { position: 'top' },
            title: { display: true, text: '心率变化趋势' }
          },
          scales: {
            y: {
              title: { display: true, text: '心率 (BPM)' },
              min: 40,
              max: 160
            },
            x: {
              ticks: {
                maxRotation: 30,
                minRotation: 30
              }
            }
          }
        }
      });
    }
  },
  mounted() {
    this.loadData();
  }
};
</script>

<style scoped>
@import "@/assets/css/analysis..css";
.ai-doctor {
  height: auto;
  margin-top: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
}
.chat-history {
  height: 600px !important; 
  overflow-y: auto;
  border: 1px solid #eee;
  padding: 10px;
  margin-bottom: 10px;
}
.message {
  margin-bottom: 10px;
  padding: 8px;
  border-radius: 4px;
}
.message.user {
  background-color: #e3f2fd;
  text-align: right;
}
.message.ai {
  background-color: #f5f5f5;
}
.input-area {
  display: flex;
}
.input-area input {
  flex: 1;
  padding: 8px;
  margin-right: 10px;
}
.input-area button {
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.input-area button:hover {
  background-color: #33a06f;
}
.ai-doctor {
  margin-top: 2rem;
  padding: 1rem;
  border: 1px solid #ddd;
  border-radius: 8px;
}
.chat-history {
  height: 300px;
  overflow-y: auto;
  margin-bottom: 1rem;
  padding: 0.5rem;
  border: 1px solid #eee;
  border-radius: 4px;
}
.message {
  margin-bottom: 0.5rem;
  padding: 0.5rem;
  border-radius: 4px;
}
.message.user {
  background-color: #e3f2fd;
  text-align: right;
}
.message.ai {
  background-color: #f5f5f5;
}
.input-area {
  display: flex;
  gap: 0.5rem;
}
.input-area input {
  flex: 1;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}
.input-area button {
  padding: 0.5rem 1rem;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.input-area button:hover {
  background-color: #0b7dda;
}

  /* 添加思考动画样式 */
  .thinking-indicator {
    color: #666;
    font-style: italic;
    padding: 10px;
    text-align: center;
  }
  .dots {
    animation: dots 1.5s steps(5, end) infinite;
  }
  @keyframes dots {
    0%, 20% { content: "."; }
    40% { content: ".."; }
    60%, 100% { content: "..."; }
  }
</style>





